package com.ctsi.commons.util.module;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

/**
 * 为模块化资源装入提供util
 * 
 * @author zhangjw
 * 
 */
public class ModuleLoad {
	private static final Logger log = LoggerFactory.getLogger(ModuleLoad.class);

	/**
	 * 从META-INF获取文件
	 * 
	 * @param cl
	 * @param resName
	 * @return
	 * @throws IOException
	 */
	public static List<URL> load(ClassLoader cl,final  String resName) throws IOException {
		assert (resName != null);
		if (cl == null) {
			cl = Thread.currentThread().getContextClassLoader();
		}

		Enumeration<URL> renum = cl.getResources("META-INF/" + resName);
		List<URL> resut = new ArrayList<URL>();
		while (renum.hasMoreElements()) {

			URL url =   renum.nextElement();
			log.debug("find {}", url);
			resut.add(url);

		}
		return resut;

	}

	/**
	 * 装入指定位置资源,不自动处理路径
	 * 
	 * @param cl
	 * @param resName
	 * @return
	 * @throws IOException
	 */
	public static List<URL> loadResources(ClassLoader cl,final  String resName) throws IOException {
		assert (resName != null);
		if (cl == null) {
			cl = Thread.currentThread().getContextClassLoader();
		}
		Enumeration<URL> renum = cl.getResources(resName);
		List<URL> resut = new ArrayList<URL>();
		while (renum.hasMoreElements()) {

			URL url =  renum.nextElement();
			log.debug("find {}", url);
			resut.add(url);
		}
		return resut;

	}
	
	public static void loadResources(final List<URL> result,ClassLoader cl,final  String resName) throws IOException {
		assert (resName != null);
		if (cl == null) {
			cl = Thread.currentThread().getContextClassLoader();
		}

		Enumeration<URL> renum = cl.getResources(resName);
 
		while (renum.hasMoreElements()) {

			URL url =  renum.nextElement();
			log.debug("find {}", url);
			result.add(url);

		}
 

	}
	public static URL loadFistResources(ClassLoader cl,final  String resName) throws IOException {
		assert (resName != null);
		if (cl == null) {
			cl = Thread.currentThread().getContextClassLoader();
		}

		Enumeration<URL> renum = cl.getResources(resName);
 
		while (renum.hasMoreElements()) {

			URL url =  renum.nextElement();
			log.debug("find {} for {}", url,resName);
			return url;

		}
		log.warn("no resource {}",resName);
		return null;

	}
	/**
	 * 指定目录下文件
	 * 
	 * @param sourcedir
	 * @return
	 */
	public String[] getFileList(final String sourcedir) {
		File source = new File(sourcedir);
		String[] result = source.list();
		if (result == null) {
			result = new String[0];
		}
		return result;
	}

	/**
	 * 装入property文件，返回map,重复项目warn
	 * 
	 * @param cl
	 * @param resName
	 * @return
	 * @throws IOException
	 */
	public static Map<String, String> loadProperty(ClassLoader cl,final  String resName) throws IOException {
		List<URL> url = load(cl, resName);
		Map<String, String> result = new HashMap<String, String>();
		for (int i = 0; i < url.size(); i++) {
			log.debug("load :{}", url.get(i));
			Properties p = load(url.get(i));
			Set<String> keyNum = p.stringPropertyNames();
			for (String key : keyNum) {

				String value = p.getProperty(key);
				if (result.containsKey(key)) {
					log.warn("the duplicate key:{} in {}", key, url.get(i));
				 
				}
				result.put(key, value);
			}
		}

		return result;

	}

	protected static Properties load(final URL url) throws IOException {
		if (url == null) {
			log.warn("url is null");
			return null;
		}
		boolean isXml = url.toString().endsWith(".xml");
		InputStream in = null;

		try {
			in = url.openStream();
		} catch (Exception urlex) {
			log.error("  Couldn't load the URL: {}", url);
			if (in != null) {
				in.close();
				in = null;
			}
		}
		if (in == null) {
			throw new IOException("Could not open resource URL " + url);
		}
		Properties p = new Properties();
		try {
			if (isXml) {
				p.loadFromXML(in);
			} else {
				p.load(in);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			in.close();
		}
		return p;
	}
}
